package com.servlet.user;

import com.entity.Code;
import com.entity.User;
import com.service.UserService;
import com.utils.JsonUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

import java.io.IOException;

/**
 * 登录用户
 * 必选参数：username、password
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 1 获取用户请求
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String validateCode = request.getParameter("code"); //用户输入的验证码
        String randStr = (String) request.getSession().getAttribute("randStr");    //真实验证码
        //TODO: 验证验证码

        //2 查询用户名密码
        JsonUtil jsonUtil = new JsonUtil();
        //3 判断
        try {
            User user = userService.findUserName(username);
            if (user.getUser_name().equals(username)){
                //用户名正确
                if (user.getUser_password().equals(password)){
                    //密码正确
                    System.out.println("---------登录成功");
                    Code code = new Code();
                    code.setCode("200");
                    code.setData(user);
                    code.setMsg("登录成功");
                    String s1 = jsonUtil.JavaToJson(code);

                    response.getWriter().print(s1);
                }else {
                    Code code = new Code();
                    code.setCode("403");
                    code.setMsg("密码错误，请重新输入");
                    String s = jsonUtil.JavaToJson(code);
                    response.getWriter().print(s);

                }
            }

        }catch (Exception e){
            Code code = new Code();
            code.setCode("400");
            code.setMsg("用户不存在");
            String s1 = jsonUtil.JavaToJson(code);

            response.getWriter().print(s1);
        }


        System.out.println("get");

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post-------------");
        doGet(request,response);

    }
}
